<?php

namespace App\Imports;


use App\Models\AgentModel;
use App\Models\DictionaryModel;
use App\Models\dispatch\DriverModel;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use stdClass;
use App\Models\DeptModel;
use App\Models\AdminRoleModel;

class CarImport implements ToCollection, WithMultipleSheets
{


    private $result;

    public function __construct() {
        $this->result = new stdClass;
    }

    public function collection(Collection $rows){
        $lines = [];
        $this->result->error = [];



        foreach ($rows as $k => $row) {
            if($k < 1) continue;

            $agent_name = $row[0];
            $type_name = $row[1];
            $car_number = $row[2];
            $driver_name = $row[3];
            $hk_driver_name = $row[4];

            $agent_find = AgentModel::where('name', $agent_name)->first();

            if(!$agent_find){
                $this->result->error[] = '第'.($k+1).'行：服务代理商不存在';
                continue;
            }
            $agent_id = $agent_find->id;

            $type_find = DictionaryModel::where('name', $type_name)->where('type_id', 3)->first();

            if(!$type_find){
                $this->result->error[] = '第'.($k+1).'行：车辆类型不存在';
                continue;
            }
            $type_id = $type_find->id;

            if($car_number == ''){
                $this->result->error[] = '第'.($k+1).'行：车牌号不能为空';
                continue;
            }

            if($driver_name != ''){
                $driver_find = DriverModel::where('name', $driver_name)->where('type', 2)->first();

                if(!$driver_find){
                    $this->result->error[] = '第'.($k+1).'行：大陆司机不存在';
                    continue;
                }
                $driver_id = $driver_find->id;
            }else{
                $driver_id = 0;
            }

            $hk_driver_find = DriverModel::where('name', $hk_driver_name)->where('type', 1)->first();
            if(!$hk_driver_find){
                $this->result->error[] = '第'.($k+1).'行：香港司机不存在';
                continue;
            }
            $hk_driver_id = $hk_driver_find->id;


            $lines[] = [
                'agent_id' => $agent_id,
                'type_id' => $type_id,
                'car_number' => $row[2],
                'driver_id' => $driver_id,
                'hk_driver_id' => $hk_driver_id,
                'volume' => $row[5],
                'weight' => $row[6],
            ];
        }

        $this->result->lines = $lines;
    }

    public function sheets(): array {
        return [ 0 => $this];
    }

    public function get_result(){
        return $this->result;
    }


}
